package com.cdeledu.dubboFutureTask;

import java.util.Map;
import java.util.concurrent.Callable;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.SynchronousQueue;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;

public class Demo {
	
	private static final ExecutorService executor = new ThreadPoolExecutor(0, 10, 60L, TimeUnit.SECONDS, new SynchronousQueue<Runnable>());
	private static final Map<String, ListenableFuture<String>> FUTURES = new ConcurrentHashMap<String, ListenableFuture<String>>();
	
	public static void main(String[] args) {
		String key = "task:1";
		ListenableFutureTask<String> listenableFutureTask = ListenableFutureTask.create(new MonitorCreator("abc"));
        listenableFutureTask.addListener(new MonitorListener(key));
        listenableFutureTask.addListener(new MonitorListener2(key));
        executor.execute(listenableFutureTask);
        FUTURES.put(key, listenableFutureTask);
	}
	
	static class MonitorCreator implements Callable<String> {

        private String s;

        public MonitorCreator(String s) {
            this.s = s;
        }

        @Override
        public String call() throws Exception {
        	Thread.sleep(2000);
            return "hello: " + s;
        }
    }

	static class MonitorListener implements Runnable {

        private String key;

        public MonitorListener(String key) {
            this.key = key;
        }

        @Override
        public void run() {
            try {
            	System.out.println("MonitorListener:" + System.currentTimeMillis());
                ListenableFuture<String> listenableFuture = Demo.FUTURES.get(key);
                System.out.println(listenableFuture.get());
            } catch (InterruptedException e) {
            	e.printStackTrace();
            } catch (ExecutionException e) {
            	e.printStackTrace();
            }
        }
    }
	
	static class MonitorListener2 implements Runnable {

        private String key;

        public MonitorListener2(String key) {
            this.key = key;
        }

        @Override
        public void run() {
            try {
            	System.out.println("MonitorListener2:" + System.currentTimeMillis());
                ListenableFuture<String> listenableFuture = Demo.FUTURES.get(key);
                System.out.println("2:" + listenableFuture.get());
            } catch (InterruptedException e) {
            	e.printStackTrace();
            } catch (ExecutionException e) {
            	e.printStackTrace();
            }
        }
    }

}
